package com.atguigu.gmall.list.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.list.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author atguigu-mqx
 */
@Component
public class ListReceiver {

    @Autowired
    private SearchService searchService;
    //  编写监听方法！
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_UPPER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            key = {MqConst.ROUTING_GOODS_UPPER}
    ))
    public void upperGoods(Long skuId , Message message, Channel channel){
        //  调用上架方法！
        try {
            if (skuId!=null){
                searchService.upperGoods(skuId);
            }
        } catch (Exception e) {
            //  如果有异常，则进行nack 第三个参数表示是否重回队列！
            //  channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            //  记录异常日志信息， 哪个skuId 上架失败了。 同时将失败的这一条数据写入数据库！
            e.printStackTrace();
        }
        //  消息确认：说明消息被消费者处理了！
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_LOWER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            key = {MqConst.ROUTING_GOODS_LOWER}
    ))
    public void lowerGoods(Long skuId , Message message, Channel channel){
        //  调用上架方法！
        try {
            if (skuId!=null){
                searchService.lowerGoods(skuId);
            }
        } catch (Exception e) {
            //  如果有异常，则进行nack 第三个参数表示是否重回队列！
            //  channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            //  记录异常日志信息， 哪个skuId 上架失败了。 同时将失败的这一条数据写入数据库！
            e.printStackTrace();
        }
        //  消息确认：说明消息被消费者处理了！
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
